package com.daqsoft.service.system;

import com.daqsoft.dao.PermissionDao;
import com.daqsoft.data.*;
import com.daqsoft.dto.ExtTreeNode;
import com.daqsoft.dto.IViewTree;
import com.daqsoft.dto.PermissionTypeEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.*;

/**
 * 权限管理服务层
 * @author 周麟东 on 14:25
 */
@Service
@Transactional
public class PermissionService  {

    private Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private PermissionDao dao;

    @Autowired
    private ModuleService moduleService;

    @Autowired
    private PermissionManageService manageService;

    @Value("${dev.server}")
    private boolean dev;


    public List<Permission> getGroupPermission(int groupId , PermissionTypeEnum permissionTypeEnum){
        return dao.findPermissionByGroupIdAndType(groupId,permissionTypeEnum);
    }

    /**
     * 获取模块显示列表
     * @return 显示列表
     */
    public List<IViewTree> getGroupModulePermissionTree(int groupId){
        //先获取模块列表
        List<Module> pModuleList = moduleService.getPModules();
        List<IViewTree> pNodeList = new ArrayList<>();
        List<Permission> permissionList = getGroupPermission(groupId,PermissionTypeEnum.CONFIG);
        for (Module pModule : pModuleList) {
            IViewTree pNode = new IViewTree();
            pNode.setTitle(pModule.getModuleName());
            pNode.setId(pModule.getId()+"");
            pNode.setExpand(true);
            List<IViewTree> nodeList = new ArrayList<>();
            //获取子节点
            for (Module cModule : pModule.getChildren()) {
                IViewTree node = new IViewTree();
                node.setTitle(cModule.getModuleName());
                node.setId(cModule.getId()+"");
                node.setExpand(true);
                //获取权限配置列表
                List<PermissionConfig> permissionConfigList = manageService.getEngineByModuleId(cModule.getId());
                //加入到子节点
                List<IViewTree> permissions = new ArrayList<>();
                for (PermissionConfig permissionConfig : permissionConfigList) {
                    IViewTree permission = new IViewTree();
                    permission.setId(permissionConfig.getId()+"");
                    permission.setTitle(permissionConfig.getName());
                    permission.setChecked(false);
                    for (Permission p : permissionList) {
                        if (p.getConfigId() == permissionConfig.getId()){
                            permission.setChecked(true);
                            break;
                        }
                    }
                    permissions.add(permission);
                }
                node.setChildren(permissions);
                nodeList.add(node);
            }
            pNode.setChildren(nodeList);
            pNodeList.add(pNode);
        }
        return pNodeList;
    }


//    /**
//     * 获取用户权限
//     * @return 用户模块权限
//     */
//    public List<Permission> getUserPermissions(User user , PermissionTypeEnum typeEnum){
//        return getUserPermissions(user.getId(),typeEnum);
//    }
//    /**
//     * 获取用户组权限
//     * @return 用户模块权限
//     */
//    public List<Permission> getUserPermissions(int userId , PermissionTypeEnum typeEnum){
//        return dao.findPermissionByUserIdAndType(userId,typeEnum);
//    }

//    /**
//     * 获取权限列表
//     * @return 返回Tree树形结构
//     */
//    public List<IViewTree> getAllPermissions(){
//        return controllers;
//    }

//    public List<IViewTree> getMethodPermissionByGroupId(int groupId) {
//
//        List<Permission> permissions = dao.findPermissionByGroupIdAndType(groupId , PermissionTypeEnum.METHOD);
//        List<IViewTree> iViewTreeList = new ArrayList<>(pathes);
//        for (IViewTree iViewTree : iViewTreeList) {
//            for (IViewTree viewTree : iViewTree.getChildren()) {
//                viewTree.setChecked(false);
//                for (Permission permission : permissions) {
//                    if (Objects.equals(permission.getMethodName(), viewTree.getId())){
//                        viewTree.setChecked(true);
//                        break;
//                    }
//                }
//            }
//        }
//
//        return iViewTreeList;
//    }

//    public void saveGroupMethodPermission(int groupId, int[] engineId) {
//        //先删除
//        dao.deletePermissionsByGroupIdAndType(groupId , PermissionTypeEnum.METHOD);
//        //再保存
//        List<Permission> permissions = new ArrayList<>();
//        for (String method : methodName) {
//            Permission permission = new Permission();
//            permission.setGroupId(groupId);
//            permission.setMethodName(method);
//            permission.setType(PermissionTypeEnum.METHOD);
//            permissions.add(permission);
//
//        }
//        dao.save(permissions);
//    }
//
    public void saveGroupModulePermission(int groupId , int [] moduleIds){
        //先删除
        dao.deletePermissionsByGroupIdAndType(groupId , PermissionTypeEnum.MODULE);
        for (int moduleId : moduleIds) {
            Permission permission = new Permission();
            permission.setGroupId(groupId);
            Module module = moduleService.get(moduleId);
            if (module == null){
                log.error("保存模块权限失败 , moduleId = {} ,未找到",moduleId);
                continue;
            }
            permission.setModule(module);
            permission.setType(PermissionTypeEnum.MODULE);
            dao.save(permission);

        }
    }
    public void saveGroupConfigPermission(int groupId, int[] configIds) {
        //先删除
        dao.deletePermissionsByGroupIdAndType(groupId , PermissionTypeEnum.CONFIG);
        //再增加
        for (int configId : configIds) {
            Permission permission = new Permission();
            permission.setGroupId(groupId);
            permission.setConfigId(configId);
            permission.setType(PermissionTypeEnum.CONFIG);
            dao.save(permission);
        }
    }

    public List<ExtTreeNode> getModulePermissionsByGroup(Group group) {
        //获取模块权限
        if (dev){
            return moduleService.getAllByTree();
        }
        if (group == null){
            log.error("获取模块权限错误 , group为空");
            return null;
        }
        //TODO 以后要改
        List<Permission> permissions = dao.findPermissionByGroupIdAndType(group.getId(),PermissionTypeEnum.MODULE);
        List<ExtTreeNode> extTreeNodes = new ArrayList<>();
        //先找到所有父级菜单
        List<Module> modules = moduleService.getPModules();
        Iterator<Module> fathers = modules.iterator();
        while (fathers.hasNext()){
            Module f = fathers.next();
            Iterator<Module> children = f.getChildren().iterator();
            while (children.hasNext()){
                Module c = children.next();
                long have = permissions.stream().filter(permission -> permission.getModule().getId() == c.getId()).count();
                if(have == 0){
                    children.remove();
                }
            }
            if (f.getChildren().isEmpty()){
                fathers.remove();
            }else {
                ExtTreeNode extTreeNode = new ExtTreeNode(f);
                extTreeNodes.add(extTreeNode);
            }
        }
        return extTreeNodes;
    }
//
//    public List<ExtTreeNode> getCheckBoxModulePermissionsByGroupId(int groupId) {
//        //获取模块权限
//        List<Permission> permissions = dao.findPermissionByGroupIdAndType(groupId,PermissionTypeEnum.MODULE);
//        List<ExtTreeNode> iViewModuleTrees = new ArrayList<>();
//        //先找到所有父级菜单
//        List<Module> modules = moduleService.getPModules();
//        for (Module module : modules) {
//            ExtTreeNode iViewModuleTree = new ExtTreeNode(module);
//            for (ExtTreeNode child : iViewModuleTree.getChildren()) {
//                child.setChecked(false);
//                for (Permission permission : permissions) {
//                    if (permission.getModuleId() == child.getId()){
//                        child.setChecked(true);
//                        break;
//                    }
//                }
//            }
//            iViewModuleTrees.add(iViewModuleTree);
//        }
//        return iViewModuleTrees;
//    }


    public List<ExtTreeNode> getModuleByUser(User user) {
        return getModulePermissionsByGroup(user.getUserGroup());
    }

    public boolean verifyPermission(User user, String path) {
        //先找到configId
        List<PermissionConfig> config = manageService.getEngineByPath(path);
        if (config.isEmpty()){
            return false;
        }
        int configIds[] = new int[config.size()];
        for (int i = 0; i < config.size(); i++) {
            configIds[i] = config.get(i).getId();
        }

        //查看用户组是否有这个权限
        int groupId = user.getUserGroup().getId();
        int count = dao.countPermissionByEngineId(configIds,groupId);
        return count>0;
    }


}
